<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useAppStore } from '../stores/appStore'
import { ElDialog, ElButton, ElInput, ElCard, ElMessageBox, ElMessage, ElTooltip, ElDivider, ElIcon } from 'element-plus'
import {
  Plus,
  Edit,
  Delete,
  Top,
  Bottom,
  TopRight,
  BottomRight,
  VideoPlay,
  CopyDocument,
  More,
  Upload,
  Download
} from '@element-plus/icons-vue'
import { v4 as uuidv4 } from 'uuid'
import { useNodeLibraryStore } from '../stores/nodeLibraryStore'
import { marked } from 'marked'
import '../styles/markdown.css'

const props = defineProps({
  node: Object,
  nodeIndex: Number,
  workflowId: String | Number,
  workflow: Object,
})

const store = useAppStore()
const showEdit = ref(false)
const editData = ref({ ...props.node })
const showMoveActions = ref(false)
const isLoading = ref(false)
const nodeLibraryStore = useNodeLibraryStore()
const showContentDialog = ref(false)
const dialogContent = ref('')
const contentType = ref('text') // 可能的值: 'text', 'json', 'markdown'
const contentSource = ref('input') // 默认为输入内容

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这个节点吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await store.deleteNode(props.workflowId, props.node.id)
    ElMessage.success('节点已删除')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleExec = async () => {
  try {
    isLoading.value = true
    await store.executeNode(props.workflowId, props.node.id)
    ElMessage.success('节点执行成功')
  } catch (error) {
    console.error('节点执行错误:', error)
    ElMessage.error(`执行失败: ${error.message}`)
  } finally {
    isLoading.value = false
  }
}

const handleExecFromHere = async () => {
  try {
    isLoading.value = true
    await store.executeFromNode(props.workflowId, props.node.id)
    ElMessage.success('执行完成')
  } catch (error) {
    console.error('执行错误:', error)
    ElMessage.error(`执行失败: ${error.message}`)
  } finally {
    isLoading.value = false
  }
}

const copyContent = async (content) => {
  try {
    await navigator.clipboard.writeText(content)
    ElMessage.success('复制成功')
  } catch (err) {
    ElMessage.error('复制失败')
    console.error('复制失败:', err)
  }
}

const getNodeTypeLabel = (type) => {
  switch (type) {
    case 'js':
      return 'JavaScript'
    case 'http':
      return 'HTTP请求'
    case 'nodata':
      return '空节点'
    case 'static':
      return '固定内容'
    default:
      return '未知类型'
  }
}

const getNodeTypeTag = (type) => {
  switch (type) {
    case 'js':
      return 'warning'
    case 'http':
      return 'success'
    case 'nodata':
      return 'info'
    case 'static':
      return 'primary'
    default:
      return ''
  }
}

// 点击其他地方时关闭移动按钮
const handleClickOutside = (event) => {
  const wrapper = event.target.closest('.node-wrapper')
  if (!wrapper || !wrapper.contains(event.target)) {
    showMoveActions.value = false
  }
}

// 添加和移除点击事件监听器
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

const handleCopyNode = async () => {
  try {
    // 深拷贝节点数据
    const nodeCopy = JSON.parse(JSON.stringify(props.node))

    // 生成新的ID
    nodeCopy.id = uuidv4()

    // 清空输入输出
    nodeCopy.input = ''
    nodeCopy.output = ''

    // 在当前节点后插入复制的节点
    await store.insertNodeAfter(props.workflowId, props.node.id, nodeCopy)

    ElMessage.success('节点复制成功')
  } catch (error) {
    console.error('复制节点失败:', error)
    ElMessage.error(`复制失败: ${error.message}`)
  }
}

const getStatusClass = (status) => {
  switch (status) {
    case '执行中':
      return 'status-running'
    case '执行成功':
      return 'status-success'
    case '执行失败':
      return 'status-error'
    default:
      return 'status-pending'
  }
}

const handleSyncToLibrary = async () => {
  try {
    // 创建一个新的模板对象
    const templateData = {
      id: props.node.id,
      name: props.node.name,
      type: props.node.type,
      content: props.node.content,
      input: props.node.input,
      output: props.node.output,
      description: props.node.description || ''
    }

    await nodeLibraryStore.addTemplate(templateData)
    ElMessage.success('节点已同步到节点库')
  } catch (error) {
    console.error('同步到节点库失败:', error)
    ElMessage.error('同步失败')
  }
}

const emit = defineEmits(['addNode', 'updateNode', 'moveNode', 'importFromLibrary'])

// 修改处理内容点击的方法
const handleContentClick = (content, source = 'input') => {
  if (!content) return;
  
  contentSource.value = source;
  
  // 设置内容类型
  try {
    JSON.parse(content);
    contentType.value = 'json';
  } catch {
    if (content.includes('#') || content.includes('```') || content.includes('*')) {
      contentType.value = 'markdown';
    } else {
      contentType.value = 'text';
    }
  }

  showContentDialog.value = true;
};

// 获取当前显示的内容
const getCurrentContent = () => {
  return contentSource.value === 'output' ? props.node.output : props.node.input;
};

// 添加获取内容预览的方法
const getContentPreview = (node) => {
  switch (node.type) {
    case 'request':
      return `${node.content?.url || '未设置'}`
    case 'static':
      return `${node.content?.text || '未设置'}`
    case 'js':
      return `${node.content?.code || '未设置'}`
    case 'append':
      return `${node.content?.text || '未设置'}`
    default:
      return ''
  }
}

// 在 script setup 中添加获取节点类型配置的方法
const getNodeTypeConfig = (type) => {
  switch (type) {
    case 'static':
      return {
        label: '静态文本',
        type: 'info'
      }
    case 'request':
      return {
        label: 'HTTP请求',
        type: 'warning'
      }
    case 'js':
      return {
        label: 'JavaScript',
        type: 'success'
      }
    case 'ai':
      return {
        label: '大模型回答',
        type: 'primary'
      }
    case 'append':
      return {
        label: '追加文本',
        type: 'danger'
      }
    default:
      return {
        label: '未知类型',
        type: 'info'
      }
  }
}

// 添加处理内容的函数，去除<think>标签及其中内容
const removeThinkTags = (content) => {
  if (!content) return '';
  
  // 使用正则表达式去除<think>标签及其中内容
  return content.replace(/<think>[\s\S]*?<\/think>/g, '');
};

// 复制去除think标签后的内容
const copyCleanContent = async () => {
  try {
    const content = contentSource.value === 'output' ? props.node.output : props.node.input;
    const cleanContent = removeThinkTags(content);
    await navigator.clipboard.writeText(cleanContent);
    ElMessage.success('已复制清理后的内容');
  } catch (err) {
    ElMessage.error('复制失败');
    console.error('复制失败:', err);
  }
};

// 修改处理内容的函数，将<think>标签内容转换为带样式的HTML
const formatThinkContent = (content) => {
  if (!content) return '';
  
  // 使用正则表达式匹配<think>标签及其内容，并替换为带样式的div
  // 添加一个特殊处理，处理未闭合的<think>标签
  let formattedContent = content;
  
  // 处理已闭合的<think>标签
  formattedContent = formattedContent.replace(/<think>([\s\S]*?)<\/think>/g, 
    '<div class="think-content"><div class="think-header">思考过程</div>$1</div>');
  
  // 处理未闭合的<think>标签（正在生成中的内容）
  const openTagIndex = formattedContent.lastIndexOf('<think>');
  if (openTagIndex !== -1 && formattedContent.indexOf('</think>', openTagIndex) === -1) {
    const thinkContent = formattedContent.substring(openTagIndex + 7); // 7是<think>的长度
    formattedContent = formattedContent.substring(0, openTagIndex) + 
      '<div class="think-content think-in-progress"><div class="think-header">思考中...</div>' + 
      thinkContent + '</div>';
  }
  
  return formattedContent;
};

// 获取带格式的内容用于显示
const getFormattedContent = () => {
  const content = contentSource.value === 'output' ? props.node.output : props.node.input;
  return formatThinkContent(content);
};
</script>

<template>
  <div class="node-wrapper" :data-node-id="node.id">
    <div class="node-card">
      <div class="node-header" @click="showEdit = true">
        <div class="node-title">
          <h5>{{ node.name }}</h5>
          <el-tag size="small" :type="getNodeTypeConfig(node.type).type">
            {{ getNodeTypeConfig(node.type).label }}
          </el-tag>
        </div>
        <span class="node-status-indicator" :class="getStatusClass(node.status)"></span>
      </div>

      <div class="node-body">
        <p v-if="node.description">{{ node.description }}</p>

        <!-- 添加节点内容显示 -->
        <div class="node-content" v-if="node.type !== 'nodata'">
          <div class="content-preview" :title="getContentPreview(node)">
            {{ getContentPreview(node) }}
            <el-button v-if="getContentPreview(node)" class="copy-content-btn" type="primary" link @click.stop="copyContent(getCurrentContent())">
              <el-icon>
                <CopyDocument />
              </el-icon>
            </el-button>
          </div>
        </div>

        <div class="io-labels">
          <div class="io-item">
            <span class="io-label input-label">输入：</span>
            <span class="io-value" @click="handleContentClick(node.input, 'input')">{{ node.input || '无' }}</span>
            <el-button v-if="node.input" class="copy-btn" type="primary" link @click.stop="copyContent(node.input)">
              <el-icon>
                <CopyDocument />
              </el-icon>
            </el-button>
          </div>
          <div class="io-item">
            <span class="io-label output-label">输出：</span>
            <span class="io-value" @click="handleContentClick(node.output, 'output')">{{ node.output || '无' }}</span>
            <el-button v-if="node.output" class="copy-btn" type="primary" link @click.stop="copyContent(node.output)">
              <el-icon>
                <CopyDocument />
              </el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <div class="node-actions">
      <!-- 左侧按钮组 -->
      <div class="action-group">
        <el-button type="success" link @click="handleExec">
          <el-icon>
            <VideoPlay />
          </el-icon>
        </el-button>
        <el-button type="success" link @click="handleExecFromHere">
          <el-icon>
            <Bottom />
          </el-icon>
        </el-button>
        <el-button type="primary" link @click="emit('addNode', workflow, node, nodeIndex)">
          <el-icon>
            <Plus />
          </el-icon>
        </el-button>
        <el-button type="primary" link @click="emit('updateNode', workflow, node, nodeIndex)">
          <el-icon>
            <Edit />
          </el-icon>
        </el-button>
        <el-button type="primary" link @click="handleCopyNode">
          <el-icon>
            <CopyDocument />
          </el-icon>
        </el-button>
        <el-button type="primary" link @click="$emit('importFromLibrary', node.id)">
          <el-icon>
            <Download />
          </el-icon>
        </el-button>
        <el-button type="danger" link @click="handleDelete">
          <el-icon>
            <Delete />
          </el-icon>
        </el-button>
        <el-button type="info" link class="more-btn" @click="showMoveActions = !showMoveActions">
          <el-icon>
            <More />
          </el-icon>
        </el-button>
      </div>

      <el-divider direction="vertical" v-show="showMoveActions" />

      <!-- 右侧按钮组 -->
      <div class="move-actions" v-show="showMoveActions">
        <el-button type="primary" link @click="$emit('moveNode', node.id, 'top')">
          <el-icon>
            <TopRight />
          </el-icon>
        </el-button>
        <el-button type="primary" link @click="$emit('moveNode', node.id, 'up')">
          <el-icon>
            <Top />
          </el-icon>
        </el-button>
        <el-button type="primary" link @click="$emit('moveNode', node.id, 'down')">
          <el-icon>
            <Bottom />
          </el-icon>
        </el-button>
        <el-button type="primary" link @click="$emit('moveNode', node.id, 'bottom')">
          <el-icon>
            <BottomRight />
          </el-icon>
        </el-button>
        <el-button type="primary" link @click="handleSyncToLibrary">
          <el-icon>
            <Upload />
          </el-icon>
        </el-button>
      </div>
    </div>

    <!-- 在现有模板的最后添加 -->
    <el-dialog v-model="showContentDialog"
      :title="contentSource === 'output' ? '输出内容' : '输入内容'" width="80%"
      :fullscreen="false" :modal="true" :close-on-click-modal="true" class="content-dialog">
      <div class="content-header">
        <h3>{{ contentSource === 'output' ? '输出内容' : '输入内容' }}</h3>
        <div class="dialog-buttons">
          <el-button
            type="primary"
            size="small"
            class="copy-dialog-btn"
            @click="copyContent(contentSource === 'output' ? node.output : node.input)"
          >
            <el-icon><CopyDocument /></el-icon>
            复制内容
          </el-button>
          <el-button
            v-if="contentSource === 'output'"
            type="success"
            size="small"
            class="copy-clean-btn"
            @click="copyCleanContent"
          >
            <el-icon><CopyDocument /></el-icon>
            仅复制回答
          </el-button>
        </div>
      </div>
      <div class="dialog-content-wrapper">
        <div v-if="contentType === 'json'" class="json-content">
          <pre>{{ contentSource === 'output' ? node.output : node.input }}</pre>
        </div>
        <div v-else-if="contentType === 'markdown'" class="markdown-content" v-html="marked(getFormattedContent())"></div>
        <div v-else class="text-content" v-html="getFormattedContent()"></div>
      </div>
    </el-dialog>
  </div>

</template>

<style scoped>
.node-wrapper {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
  position: relative;
  /* 添加相对定位 */
}

.node-card {
  flex: 1;
  background: white;
  border-radius: 6px;
  padding: 12px;
  max-width: 500px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.node-actions {
  display: flex;
  gap: 8px;
  padding: 8px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.action-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.move-actions {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.node-actions .el-divider--vertical {
  height: auto;
  margin: 0 4px;
}

/* 确保图标大小一致 */
.node-actions :deep(.el-icon) {
  font-size: 16px;
}

/* 调整按钮样式 */
.node-actions :deep(.is-link) {
  padding: 4px;
  height: auto;
  margin: 0;
}

/* 其他现有样式保持不变 */
.node-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.node-status-indicator {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.status-pending {
  background: #909399;
  /* 灰色 - 未执行 */
}

.status-running {
  background: #e6a23c;
  /* 橙色 - 执行中 */
  animation: pulse 1s infinite;
}

.status-success {
  background: #67c23a;
  /* 绿色 - 执行成功 */
}

.status-error {
  background: #f56c6c;
  /* 红色 - 执行失败 */
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }

  50% {
    transform: scale(1.2);
    opacity: 0.5;
  }

  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.io-labels {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 8px;
  font-size: 12px;
}

.input-label {
  color: #409eff;
}

.output-label {
  color: #67c23a;
}

.io-item {
  display: flex;
  align-items: flex-start;
  gap: 4px;
  position: relative;
  padding-right: 24px;
  /* 为复制按钮留出空间 */
}

.io-value {
  /* max-width: 200px; */
  display: -webkit-box;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  flex: 1;
  cursor: pointer;
}

.io-value:hover {
  color: #409eff;
}

.copy-btn {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  padding: 2px;
  font-size: 14px;
}

.copy-btn :deep(.el-icon) {
  font-size: 14px;
}

.node-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-title h5 {
  margin: 0;
}

:deep(.el-tag) {
  height: 20px;
  line-height: 18px;
  font-size: 11px;
}

/* 添加过渡动画 */
.move-actions {
  transition: all 0.3s ease;
}

.json-content {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 4px;
  font-family: monospace;
  white-space: pre-wrap;
  word-break: break-all;
}

.markdown-content {
  padding: 16px;
  line-height: 1.6;
}

.text-content {
  padding: 16px;
  white-space: pre-wrap;
  word-break: break-all;
}

.node-content {
  margin: 8px 0;
  padding: 4px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  position: relative;
}

.content-preview {
  font-size: 12px;
  color: #606266;
  line-height: 1.5;
  max-height: 9em;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 6;
  -webkit-box-orient: vertical;
  white-space: pre-wrap;
  word-break: break-all;
  padding-right: 24px; /* 为复制按钮预留空间 */
}

.copy-content-btn {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  padding: 2px;
  font-size: 14px;
}

.copy-content-btn :deep(.el-icon) {
  font-size: 14px;
}

:deep(.el-dialog.content-dialog) {
  margin: 5vh auto !important;
  height: 90vh;
  display: flex;
  flex-direction: column;
}

:deep(.content-dialog .el-dialog__body) {
  flex: 1;
  padding: 0;
  overflow: hidden;
}

.dialog-content-wrapper {
  height: 100%;
  padding: 20px;
  overflow-y: auto;
  box-sizing: border-box;
}

.json-content,
.text-content,
.markdown-content {
  margin: 0;
  padding: 16px;
  box-sizing: border-box;
}

/* 自定义滚动条样式 */
.dialog-content-wrapper::-webkit-scrollbar {
  width: 6px;
}

.dialog-content-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.dialog-content-wrapper::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.dialog-content-wrapper::-webkit-scrollbar-thumb:hover {
  background: #999;
}

.content-header {
  position: relative;
  padding-right: 80px; /* 为复制按钮预留空间 */
}

.dialog-buttons {
  display: flex;
  gap: 8px;
}

.copy-dialog-btn,
.copy-clean-btn {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 添加思考内容的样式 */
:deep(.think-content) {
  margin: 10px 0;
  padding: 10px;
  background-color: #f8f8f8;
  border-left: 4px solid #e6a23c;
  border-radius: 4px;
  font-size: 0.95em;
  color: #606266;
}

/* 添加正在生成中的思考内容样式 */
:deep(.think-in-progress) {
  border-left: 4px solid #409EFF;
}

:deep(.think-in-progress .think-header) {
  color: #409EFF;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { opacity: 0.6; }
  50% { opacity: 1; }
  100% { opacity: 0.6; }
}

:deep(.think-header) {
  font-weight: bold;
  margin-bottom: 8px;
  color: #e6a23c;
  font-size: 0.9em;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 0 20px;
}

.dialog-buttons {
  display: flex;
  gap: 8px;
}

.copy-dialog-btn,
.copy-clean-btn {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>
